package com.nCoV.EpidemicSurveillance.config;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import org.springframework.security.core.Authentication;

import com.fasterxml.jackson.databind.ObjectMapper;

/** 
* @author 作者 罗穆健: 
* @version 创建时间：2020年1月5日 下午6:52:01 
* 类说明  密码正确的跳转
*/
@Service
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //什么都不做的话，那就直接调用父类的方法
        /*super.onAuthenticationSuccess(request, response, authentication);*/
 
        //这里可以根据实际情况，来确定是跳转到页面或者json格式。
        //如果是返回json格式，那么我们这么写
    	Map<String,Object> map = new HashMap<String,Object>();
        map.put("code",200);
        map.put("message","登录成功");
        map.put("data",authentication);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(objectMapper.writeValueAsString(map));
        out.flush();
        out.close();
    }
//    在未登录的情况下访问某些页面被拦截，跳转到登录页面，然后现在需要登录成功之后跳转到登录之前的页面
//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
//            Authentication authentication) throws IOException, ServletException {
//      response.setContentType("application/json;charset=utf-8");
//
//      RequestCache cache = new HttpSessionRequestCache();
//      SavedRequest savedRequest = cache.getRequest(request, response);
//      String url = savedRequest.getRedirectUrl();
//      
//      response.sendRedirect(url);
//      
//      
//    }
}
 